<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Order extends MY_Controller {
	/**
	 * 假索引
	 * @var ConsumerMallModel
	 */
	public $mMall;
	public function __construct(){
		parent::__construct();		
	}
	
	/**
	 * 首页
	 */
	public function index(){
        $this->loadModel('AdmShippingModel', 'mShipping', 'admin');

        $ship = $this->mShipping->getList();    // 获取快递公司

        $data = array(
            'title'=>'礼品订单',
            'ship' => $ship,
        );
		$this->view('mall/order/home', $data, 'datatable,validation,select2,datepicker');
	}
	
	/**
	 * 详情
	 */
	public function details(){
		$this->loadModel('ConsumerMallModel', 'mMall', 'consumer');
		$info = $this->mMall->getLogInfo(get('id'));
		if ( ! $info){
			show_404();
		}
// 		print_r($info);
		$data = array(
				'title'=>'详情',
				'info'=>$info,
		);
		
		$this->view('mall/order/details', $data, '');
	}
	
	/**
	 * 获取列表
	 */
	public function getList(){
		$this->loadModel('ConsumerMallModel', 'mMall', 'consumer');
		$data = $this->mMall->adminGetLogList();
//		p($data);
		foreach ($data['data'] as $k=>$v){
			$product_param = json_decode($v['product_param'],true);
			$address_param = json_decode($v['address_param'],true);
			$express_param = json_decode($v['express_param'],true);

			$data['aaData'][$k][] = $v['code'];
			$data['aaData'][$k][] = isset($product_param['product_name']) ? $product_param['product_name'] : '暂无';
			$data['aaData'][$k][] = isset($product_param['number']) ? $product_param['number'] : '0';
			$data['aaData'][$k][] = isset($this->mMall->config['type'][$v['type']]) ? $this->mMall->config['type'][$v['type']]:'暂无';
			$data['aaData'][$k][] = '<span style="color:green">'.abs($v['integral']).'</span>';
			$data['aaData'][$k][] = isset($address_param['address']) ? $address_param['address'] : '暂无';
			if ($v['status'] == 2) {
                $data['aaData'][$k][] = '<a href="javascript:" data-placement="left" class="popovers" data-trigger="hover" data-content="
									快递公司:' . (isset($express_param['company']) ? $express_param['company'] : '暂无') . '<br>
									快递单号:' . (isset($express_param['code']) ? $express_param['code'] : '暂无')
                    . '" data-original-title="快递信息">快递信息</a>';
            }else{
                $data['aaData'][$k][] = '';
            }
			$data['aaData'][$k][] = date('Y-m-d H:i:s',$v['addtime']);
			$data['aaData'][$k][] = $this->mMall->getStatus($v['status'],true);
			
			//详情
			$btnConfig = adminCreateBtn(array(
							'label' => '详情',
							'attr' => array(
									'href' => getUrl('mall/order/details?id='.$v['id']),
									'class' => 'btn btn-xs green-stripe default',
							),
							'tag' => 'a',
					));
			
			//未处理
			if ($v['status'] == 1){
				//处理中
				$btnConfig .=' '.adminCreateBtn(array(
						'label' => $this->mMall->getStatus(2),
//						'icon' => '',
//						'attr' => array(
//								'href' => getUrl('mall/order/status?id='.$v['id'].'&status=2'),
//								'class' => 'ajax-request-btn btn btn-xs yellow-stripe default',
//								'alert-message'=>'确定要将“'.$product_param['product_name'].'”状态更改为'.$this->mMall->getStatus(2).'?',
//						),
//						'tag' => 'a',
                        'attr' => array(
                            'href' => 'javascript:;',
                            'class' => 'btn btn-xs red-stripe default delivery',
                            'data-id' => $v['id'],
                            'data-name' => $v['code']
                        ),
                        'tag' => 'a',
                        'permissions' => array(
                            'module' => 'classes',
                            'key' => 'edit'
                        )
				));
				
				//退积分
				$btnConfig .=' '.adminCreateBtn(array(
						'label' => $this->mMall->getStatus(3),
						'icon' => '',
						'attr' => array(
								'href' => getUrl('mall/order/status?id='.$v['id'].'&status=3'),
								'class' => 'ajax-request-btn btn btn-xs yellow-stripe default',
								'alert-message'=>'确定要将订单：“'.$v['code'].'”的积分退回?',
						),
						'tag' => 'a',
						'permissions' => array(
								'module' => 'classes',
								'key' => 'edit'
						)
				));
			}
			
			$data['aaData'][$k][] = $btnConfig;
		}
		
		unset($data['data']);
		echo json_encode($data);
	}

    /**
     * 发货
     */
    public function delivery(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
            array('express', '快递公司', 'required'),
            array('express_bill', '快递单号', 'required'),
        );
        $this->formDataValidation($vConf);
        $id = (int)post('id');
        // 查看订单是否存在
        $this->loadModel('ConsumerMallModel', 'mMall','consumer');

        $info = $this->mMall->getLogInfo($id);
        if(!$info){
            $this->ajaxReturn(0, '积分订单不存在');
        }
        if ($info['status'] != 1){
            $this->ajaxReturn(0, '此订单不能发货');
        }

        $express = trim(post('express'));
        $express_bill = trim(post('express_bill'));

        $result = KDNiao()->getSingleNumberRecognitionByJson($express_bill);
        $result = json_decode($result, true);
        if(!$result['Success']){
            $this->ajaxReturn(0, '快递单号有误');
        }
        $expressCode = false;
        $express_param = array(
            'company' => $express,
            'code' => $express_bill,
        );
        foreach ($result['Shippers'] as $k => $v){
            if ($v['ShipperName'] == $express_param['company']){
                $expressCode = $v['ShipperCode'];
            }
        }

        if (!$expressCode){
            $this->ajaxReturn(0, '快递单号有误');
        }

        // 添加物流信息
        $tA = $this->mMall->saveLog(array('status' => 2,'express_param'=>json_encode($express_param)), $id);
        if (!$tA){

            $this->ajaxReturn(0, '保存失败');
        }

        $this->ajaxReturn(1, '保存成功');
    }

	/**
	 * 更改状态
	 */
	public function status(){
		
		$id = get('id');
		$status = get('status');
		if (! $id || ! $status || ! in_array($status, array(2,3))){
			$this->ajaxReturn(0,'参数错误');
		}
		
		$this->loadModel('ConsumerMallModel', 'mMall','consumer');
		$this->loadModel('ConsumerUserModel', 'mCuser','consumer');

		$info = $this->mMall->getLogInfo($id);
		if(!$info){
		    $this->ajaxReturn(0, '积分订单不存在');
        }

        $this->db->trans_begin();
		if($status == 3){
		    //退回积分
            $userInfo = $this->mCuser->getInfo($info['consumer_id']);
            if(!$userInfo){
                $this->ajaxReturn(0, '消费者不存在');
            }
            if(!($this->mCuser->save(array('integral'=>$userInfo['integral'] + abs($info['integral'])), $info['consumer_id']))){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '保存失败');
            }
            //增加积分记录日志
            $log = array(
                'consumer_id' => $info['consumer_id'],
                'integral' => abs($info['integral']),
                'type' => 8,
                'status' => 2,
                'addtime' => time(),
            );
            if(!($this->mMall->saveLog($log))){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '保存失败');
            }
        }
        //保存记录
		if( ! $this->mMall->saveLog(array('status'=>$status),$id)){
            $this->db->trans_rollback();
			$this->ajaxReturn(0,'保存失败');
		}

        $this->db->trans_commit();
		$this->ajaxReturn(1,'保存成功');
	}
}
